package com.example.sys.authority.service.impl;

import com.example.core.hql.HQLInfo;
import com.example.core.service.impl.BaseServiceImpl;
import com.example.shiro.utils.UserAuthInfo;
import com.example.sys.authority.dao.SysAuthorityDao;
import com.example.sys.authority.model.SysAuthority;
import com.example.sys.authority.service.SysAuthorityService;
import com.example.utils.StringUtils;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;

@Service
public class SysAuthorityServiceImpl extends BaseServiceImpl<SysAuthorityDao, SysAuthority> implements SysAuthorityService {

    @Override
    public List<String> getModelAuthority(UserAuthInfo userAuthInfo, String modelName) throws Exception {
        return this.getBaseDao().getModelIdAuthority(modelName, userAuthInfo.getUserAuthId());
    }

    @Override
    public Boolean checkAuthority(UserAuthInfo userAuthInfo, String modelName, String modelId, int fdKey) throws Exception {
        List<String> elements = this.getBaseDao().getModelAuthorityElements(modelName, modelId, fdKey);
        if (elements.isEmpty()) {
            return false;
        }
        return !Collections.disjoint(userAuthInfo.getUserAuthId(), elements);
    }

    @Override
    public HQLInfo buildQueryHQL(UserAuthInfo userAuthInfo, HQLInfo hqlInfo) throws Exception {
        hqlInfo.setWhereBlock(StringUtils.linkString(hqlInfo.getWhereBlock(), " and ", hqlInfo.getModelTable() + ".fdId in (" + "select sysAuthority.fdModelId from SysAuthority sysAuthority where sysAuthority.fdModelName =:modelName and sysAuthority.fdElement.fdId in (:authIds)" + ")"));
        hqlInfo.setParameter("modelName", hqlInfo.getModelName());
        hqlInfo.setParameter("authIds", userAuthInfo.getUserAuthId());
        return hqlInfo;
    }
}
